﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TelerikConnect.Web.DBConnect;

namespace Kendo.Mvc.Examples.Controllers
{
    public partial class UploadController : Controller
    {
        private TelerikDb db = new TelerikDb();

        public ActionResult Async()
        {
            return View();
        }

        public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
        {
            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    /// TODO Secure the uploads, limit to image files only and check file size

                    var fileName = Path.GetFileName(file.FileName);
                    fileName = string.Format("{0}{1}", User.Identity.Name, fileName.Substring(fileName.LastIndexOf('.')));
                    var physicalPath = Path.Combine(Server.MapPath("~/Content/Avatars"), fileName);

                    // The files are not actually saved in this demo
                    file.SaveAs(physicalPath);
                    db.UserProfiles.Single(u => u.UserName == User.Identity.Name).Avatar = string.Format("/Content/Avatars/{0}", fileName);
                    db.SaveChanges();
                }
            }

            // Return an empty string to signify success
            return Content("");
        }

        //public ActionResult Remove(string[] fileNames)
        //{
        //    // The parameter of the Remove action must be called "fileNames"

        //    if (fileNames != null)
        //    {
        //        foreach (var fullName in fileNames)
        //        {
        //            var fileName = Path.GetFileName(fullName);
        //            var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

        //            // TODO: Verify user permissions

        //            if (System.IO.File.Exists(physicalPath))
        //            {
        //                // The files are not actually removed in this demo
        //                // System.IO.File.Delete(physicalPath);
        //            }
        //        }
        //    }

        //    // Return an empty string to signify success
        //    return Content("");
        //}
    }
}